<template>
  <div id="app">
    <button @click="returnFn" class="btn btn-primary retrunBUtton">
      <i class="icon">⚡</i> 返回
    </button>
    <div class="container">
      <header>
        <h1>时间戳转换工具</h1>
        <p class="subtitle">支持秒级/毫秒级时间戳与日期时间相互转换</p>
      </header>

      <div class="main-content">
        <!-- 输入区域 -->
        <div class="input-section">
          <div class="section-title">
            <h2>输入时间戳或日期</h2>
            <div class="button-group">
              <button @click="useCurrentTime" class="btn btn-primary">
                <i class="icon">⏰</i> 当前时间
              </button>
              <button @click="clearInput" class="btn btn-secondary">
                <i class="icon">🗑️</i> 清空
              </button>
            </div>
          </div>

          <div class="input-controls">
            <div class="input-group">
              <label>时间戳：</label>
              <input
                type="text"
                v-model="timestampInput"
                placeholder="输入时间戳（秒或毫秒）"
                class="input-field"
                @input="convertTimestampToDate"
              />
            </div>

            <div class="radio-group">
              <label class="radio-label">
                <input type="radio" v-model="timestampUnit" value="seconds" class="radio-input" />
                <span class="radio-custom"></span>
                秒级时间戳（10位）
              </label>
              <label class="radio-label">
                <input
                  type="radio"
                  v-model="timestampUnit"
                  value="milliseconds"
                  class="radio-input"
                />
                <span class="radio-custom"></span>
                毫秒级时间戳（13位）
              </label>
            </div>

            <div class="input-group">
              <label>日期时间：</label>
              <input
                type="datetime-local"
                v-model="dateTimeInput"
                class="input-field"
                @input="convertDateToTimestamp"
              />
            </div>

            <div class="input-group">
              <label>时区：</label>
              <select v-model="selectedTimezone" class="select-field">
                <option v-for="tz in timezones" :key="tz.value" :value="tz.value">
                  {{ tz.label }}
                </option>
              </select>
            </div>
          </div>

          <div v-if="hasError" class="error-message"><i class="icon">❌</i> {{ errorMessage }}</div>
        </div>

        <!-- 转换结果 -->
        <div class="output-section">
          <div class="section-title">
            <h2>转换结果</h2>
            <div class="button-group">
              <button
                @click="copyToClipboard"
                class="btn btn-success"
                :disabled="!conversionResult"
              >
                <i class="icon">📋</i> {{ copyButtonText }}
              </button>
            </div>
          </div>

          <div class="result-cards">
            <div class="result-card">
              <h3>时间戳</h3>
              <div class="result-value">{{ conversionResult.timestamp || '--' }}</div>
              <div class="result-meta">
                格式：{{
                  conversionResult.timestamp
                    ? conversionResult.timestamp.length === 10
                      ? '秒级'
                      : '毫秒级'
                    : '--'
                }}
              </div>
            </div>

            <div class="result-card">
              <h3>本地时间</h3>
              <div class="result-value">{{ conversionResult.localTime || '--' }}</div>
              <div class="result-meta">时区：本地时间</div>
            </div>

            <div class="result-card">
              <h3>UTC时间</h3>
              <div class="result-value">{{ conversionResult.utcTime || '--' }}</div>
              <div class="result-meta">时区：UTC</div>
            </div>

            <div class="result-card" v-if="selectedTimezone !== 'local'">
              <h3>指定时区时间</h3>
              <div class="result-value">{{ conversionResult.customTime || '--' }}</div>
              <div class="result-meta">时区：{{ getTimezoneLabel(selectedTimezone) }}</div>
            </div>
          </div>

          <div class="additional-info" v-if="conversionResult.timestamp">
            <h3>其他信息</h3>
            <div class="info-grid">
              <div class="info-item">
                <span class="info-label">星期：</span>
                <span class="info-value">{{ conversionResult.dayOfWeek }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">年份：</span>
                <span class="info-value">{{ conversionResult.year }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">季度：</span>
                <span class="info-value">{{ conversionResult.quarter }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">是否闰年：</span>
                <span class="info-value">{{ conversionResult.isLeapYear ? '是' : '否' }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <footer>
        <p>时间戳转换工具 v1.0 | 使用Vue 3开发</p>
      </footer>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
// 响应式数据
const timestampInput = ref('')
const dateTimeInput = ref('')
const timestampUnit = ref('seconds')
const selectedTimezone = ref('local')
const hasError = ref(false)
const errorMessage = ref('')
const copyButtonText = ref('复制结果')
const Router = useRouter()
// 转换结果
const conversionResult = ref({
  timestamp: '',
  localTime: '',
  utcTime: '',
  customTime: '',
  dayOfWeek: '',
  year: '',
  quarter: '',
  isLeapYear: false
})
const returnFn = () => {
  Router.go(-1)
}
// 时区选项
const timezones = ref([
  { value: 'local', label: '本地时间' },
  { value: 'UTC', label: 'UTC' },
  { value: 'America/New_York', label: '美国纽约 (UTC-5)' },
  { value: 'America/Los_Angeles', label: '美国洛杉矶 (UTC-8)' },
  { value: 'Europe/London', label: '英国伦敦 (UTC+0)' },
  { value: 'Europe/Paris', label: '法国巴黎 (UTC+1)' },
  { value: 'Asia/Shanghai', label: '中国上海 (UTC+8)' },
  { value: 'Asia/Tokyo', label: '日本东京 (UTC+9)' },
  { value: 'Australia/Sydney', label: '澳大利亚悉尼 (UTC+10)' }
])

// 监听时区变化
watch(selectedTimezone, () => {
  if (timestampInput.value || dateTimeInput.value) {
    if (timestampInput.value) {
      convertTimestampToDate()
    } else {
      convertDateToTimestamp()
    }
  }
})

// 监听时间戳单位变化
watch(timestampUnit, () => {
  if (timestampInput.value) {
    convertTimestampToDate()
  }
})

// 使用当前时间
const useCurrentTime = () => {
  const now = new Date()
  if (timestampUnit.value == 'seconds') {
    timestampInput.value = Math.floor(now.getTime() / 1000).toString()
  } else {
    timestampInput.value = Math.floor(now.getTime()).toString()
  }

  convertTimestampToDate()
}

// 清空输入
const clearInput = () => {
  timestampInput.value = ''
  dateTimeInput.value = ''
  conversionResult.value = {
    timestamp: '',
    localTime: '',
    utcTime: '',
    customTime: '',
    dayOfWeek: '',
    year: '',
    quarter: '',
    isLeapYear: false
  }
  clearError()
}

// 时间戳转日期
const convertTimestampToDate = () => {
  if (!timestampInput.value.trim()) {
    clearInput()
    return
  }

  try {
    // 验证输入是否为数字
    const timestamp = timestampInput.value.trim()
    if (!/^\d+$/.test(timestamp)) {
      throw new Error('时间戳必须为数字')
    }

    // 根据单位转换时间戳
    let timestampValue = parseInt(timestamp)
    if (timestampUnit.value === 'seconds') {
      // 如果是秒级时间戳，转换为毫秒
      timestampValue = timestampValue * 1000
    }

    // 验证时间戳范围（1900-2100年）
    const minTimestamp = -2208988800000 // 1900年
    const maxTimestamp = 4102444800000 // 2100年
    if (timestampValue < minTimestamp || timestampValue > maxTimestamp) {
      throw new Error('时间戳超出有效范围（1900-2100年）')
    }

    const date = new Date(timestampValue)

    // 验证日期有效性
    if (isNaN(date.getTime())) {
      throw new Error('无效的时间戳')
    }

    // 更新日期时间输入框
    dateTimeInput.value = formatDateForInput(date)

    // 设置转换结果
    updateConversionResult(date)
    clearError()
  } catch (error) {
    showError('转换失败: ' + error.message)
  }
}

// 日期转时间戳
const convertDateToTimestamp = () => {
  if (!dateTimeInput.value) {
    clearInput()
    return
  }

  try {
    const date = new Date(dateTimeInput.value)

    // 验证日期有效性
    if (isNaN(date.getTime())) {
      throw new Error('无效的日期时间')
    }

    // 根据单位设置时间戳
    let timestampValue
    if (timestampUnit.value === 'seconds') {
      timestampValue = Math.floor(date.getTime() / 1000)
    } else {
      timestampValue = date.getTime()
    }

    timestampInput.value = timestampValue.toString()
    updateConversionResult(date)
    clearError()
  } catch (error) {
    showError('转换失败: ' + error.message)
  }
}

// 更新转换结果
const updateConversionResult = (date) => {
  // 时间戳
  const timestamp = timestampUnit.value === 'seconds'
    ? Math.floor(date.getTime() / 1000)
    : date.getTime()

  // 本地时间
  const localTime = formatDate(date, 'local')

  // UTC时间
  const utcTime = formatDate(date, 'UTC')

  // 指定时区时间
  let customTime = ''
  try {
    customTime = formatDateForTimezone(date, selectedTimezone.value)
  } catch (error) {
    console.warn('时区转换失败:', error)
    customTime = '时区不支持'
  }

  // 其他信息
  const dayOfWeek = getDayOfWeek(date)
  const year = date.getFullYear()
  const quarter = Math.floor((date.getMonth() + 3) / 3)
  const isLeapYear = isLeapYearCheck(year)

  conversionResult.value = {
    timestamp: timestamp.toString(),
    localTime,
    utcTime,
    customTime,
    dayOfWeek,
    year: year.toString(),
    quarter: `第${quarter}季度`,
    isLeapYear
  }
}

// 格式化日期为输入框格式
const formatDateForInput = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')

  return `${year}-${month}-${day}T${hours}:${minutes}`
}

// 格式化日期显示
const formatDate = (date, timezone) => {
  const options = {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    timeZone: timezone === 'local' ? undefined : timezone,
    timeZoneName: 'short'
  }

  return date.toLocaleString('zh-CN', options)
}

// 格式化指定时区时间
const formatDateForTimezone = (date, timezone) => {
  if (timezone === 'local') {
    return formatDate(date, 'local')
  }

  const options = {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    timeZone: timezone,
    timeZoneName: 'short'
  }

  return date.toLocaleString('zh-CN', options)
}

// 获取星期几
const getDayOfWeek = (date) => {
  const days = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
  return days[date.getDay()]
}

// 检查是否为闰年
const isLeapYearCheck = (year) => {
  return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0
}

// 获取时区标签
const getTimezoneLabel = (timezone) => {
  const tz = timezones.value.find(t => t.value === timezone)
  return tz ? tz.label : timezone
}

// 复制到剪贴板
const copyToClipboard = async () => {
  if (!conversionResult.value.timestamp) return

  const resultText = `时间戳: ${conversionResult.value.timestamp}
本地时间: ${conversionResult.value.localTime}
UTC时间: ${conversionResult.value.utcTime}
${selectedTimezone.value !== 'local' ? `指定时区时间: ${conversionResult.value.customTime}` : ''}`

  try {
    await navigator.clipboard.writeText(resultText)
    copyButtonText.value = '已复制!'
    setTimeout(() => {
      copyButtonText.value = '复制结果'
    }, 2000)
  } catch (err) {
    console.error('复制失败: ', err)
    copyButtonText.value = '复制失败'
    setTimeout(() => {
      copyButtonText.value = '复制结果'
    }, 2000)
  }
}

// 错误处理
const showError = (message) => {
  hasError.value = true
  errorMessage.value = message
}

const clearError = () => {
  hasError.value = false
  errorMessage.value = ''
}

// 初始化时使用当前时间
useCurrentTime()
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

#app {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  position: relative;
}
.retrunBUtton {
  position: absolute;
  top: 100px;
  right: 100px;
}
.container {
  width: 100%;
  max-width: 1300px;
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  overflow: hidden;
}

header {
  background: linear-gradient(to right, #667eea, #764ba2);
  color: white;
  padding: 20px 30px;
  text-align: center;
}

h1 {
  font-size: 32px;
  margin-bottom: 5px;
}

.subtitle {
  font-size: 20px;
  opacity: 0.9;
}

.main-content {
  display: flex;
  flex-direction: column;
  padding: 25px;
}

.input-section,
.output-section {
  margin-bottom: 25px;
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.section-title h2 {
  font-size: 20px;
  color: #333;
}

.button-group {
  display: flex;
  gap: 10px;
}

.btn {
  padding: 8px 15px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 20px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 5px;
  transition: all 0.3s ease;
}

.btn-primary {
  background: linear-gradient(to right, #667eea, #764ba2);
  color: white;
}

.btn-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(102, 126, 234, 0.3);
}

.btn-secondary {
  background: #f0f0f0;
  color: #333;
}

.btn-secondary:hover {
  background: #e0e0e0;
}

.btn-success {
  background: linear-gradient(to right, #4ecdc4, #44a08d);
  color: white;
}

.btn-success:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(78, 205, 196, 0.3);
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none !important;
  box-shadow: none !important;
}

.input-controls {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.input-group {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.input-group label {
  font-weight: 500;
  color: #555;
}

.input-field,
.select-field {
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 20px;
  outline: none;
  transition: border-color 0.3s;
}

.input-field:focus,
.select-field:focus {
  border-color: #667eea;
}

.radio-group {
  display: flex;
  gap: 20px;
  margin: 10px 0;
}

.radio-label {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  font-size: 20px;
}

.radio-input {
  display: none;
}

.radio-custom {
  width: 18px;
  height: 18px;
  border: 2px solid #ddd;
  border-radius: 50%;
  position: relative;
  transition: all 0.3s;
}

.radio-input:checked + .radio-custom {
  border-color: #667eea;
}

.radio-input:checked + .radio-custom::after {
  content: '';
  width: 10px;
  height: 10px;
  background: #667eea;
  border-radius: 50%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.result-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 15px;
  margin-bottom: 20px;
}

.result-card {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  border-left: 4px solid #667eea;
}

.result-card h3 {
  font-size: 20px;
  color: #666;
  margin-bottom: 8px;
}

.result-value {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin-bottom: 5px;
  word-break: break-all;
}

.result-meta {
  font-size: 16px;
  color: #888;
}

.additional-info {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
}

.additional-info h3 {
  font-size: 20px;
  color: #333;
  margin-bottom: 10px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 10px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 5px 0;
  border-bottom: 1px solid #eee;
}

.info-label {
  font-weight: 500;
  color: #666;
}

.info-value {
  color: #333;
}

footer {
  text-align: center;
  padding: 15px;
  background-color: #f5f5f5;
  color: #666;
  font-size: 18px;
}

.icon {
  font-style: normal;
}

.error-message {
  margin-top: 10px;
  padding: 10px;
  background-color: #ffeaea;
  border-left: 4px solid #e74c3c;
  color: #c0392b;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .section-title {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .button-group {
    width: 100%;
    justify-content: flex-end;
  }

  .radio-group {
    flex-direction: column;
    gap: 10px;
  }

  .result-cards {
    grid-template-columns: 1fr;
  }

  .info-grid {
    grid-template-columns: 1fr;
  }
}
</style>